<template>
  <div>
    <el-row :gutter="24">

      <el-col :span="18">
        <h2 style="text-align: center;margin-top: 0px;">发送联系人</h2>
        <el-card class="box-card" style="max-height: 400px;overflow: auto;height: 200px;width: 100%">
          <!--       <draggable
                   tag="el-collapse"
                   class="dragArea list-group2"
                   :list="list2"
                   group="comp"
                   @change="log"
                 >-->
          <!--        <el-collapse
                    multiple
                    class="list-group-item2 left"
                    v-for="(element,index) in list2"
                    :key="index"
                    v-model="activeNames"
                    @change="handleChange"
                  >
                    <el-collapse-item class="collapse-item" :name="element.id">
                      <template slot="title">
                        <span>{{element.name}}</span>
                        <i class="el-icon-circle-close" @click.stop="deleteItem(index)"></i>
                      </template>
                    </el-collapse-item>

                  </el-collapse>-->
          <!--         <div round class="list-group-item3" v-for="(user,index) in list2" :key="index">
                     {{user.name}}
                     <i class="el-icon-circle-close item" @click.stop="deleteItem(index)"></i>
                   </div>-->
          <el-tag
            style="margin-right: 5px"
            :key="index"
            v-for="(tag,index) in list2"
            closable
            :disable-transitions="false"
            @close="deleteItem(index)">
            {{tag.name}}
          </el-tag>
          <!--       </draggable>-->
        </el-card>
        <el-form  :model="form" label-width="180px" ref="dataForm" :rules="dataRule" style="margin-top: 50px">
          <el-row>
            <el-form-item label="短信模版" prop="template">
              <el-select v-model="form.template" placeholder="请选择短信模版" @change="changeTemplateText">
                <el-option v-for="(item, index) in templates" :key="index" :label="item.name"
                           :value="item.id" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-col :span="18">
              <el-form-item :key="index" :label="'替换${'+item+'}内容'" v-for="(item,index) in codeStr" :prop="item">
                <!--         <el-input type="text" v-model="param[item]" :placeholder="'请输入替换模版中${'+item+'}的内容'" @input="replace(item)"></el-input>-->
                <el-input type="text" v-model="form[item]" :placeholder="'请输入替换模版中${'+item+'}的内容'" @input="replace(item)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="模版显示 :">
                <span>{{templateText1}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="18" v-if="showHint">
              <el-form-item>
                <span style="color: #c6ccd4;font-size: 5px">计费说明：当前内容字数为<span style="color: orange">{{smsgMessageWord}}</span>，按照<span style="color: orange">{{smsgNumber}}</span>条短信发送并计费。</span>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item>

                <el-button type="primary" @click="onSubmit">立即发送</el-button>
                <el-button @click="close" >取消</el-button>

              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </el-col>
      <el-col :span="6" >
        <el-card class="box-card" style="max-height: 700px;overflow: auto;height: 800px" >

          <span style="display: flex;flex-wrap: wrap-reverse;flex-direction: row;justify-content: space-around"><el-button type="text" @click="select" style="margin-top: 15px;margin-left: -50px">{{selectOrCancel}}</el-button><h2 style="text-align: center;margin-top: 0px">联系人</h2><el-button type="text" @click="selecedContacts" style="margin-top: 15px;margin-right: -50px">确定</el-button></span>

          <!--       <el-collapse v-model="activeNames1" @change="handleChange" accordion style="max-height: 100px;">

                   <el-collapse-item v-for="(contact,index) in contacts" :key="contact.id">
                     <template slot="title">
                       <el-checkbox v-if="isSelect" v-model="contact.checked" @change="updateChecked(contact,index)"  style="margin-right: 10px"></el-checkbox> {{contact.name}}

                     </template>
          &lt;!&ndash;           <draggable
                       class="dragArea list-group"
                       :list="contact.children"
                       :group="{ name: 'comp', pull: 'clone', put: false }"
                       @change="log"
                     >&ndash;&gt;
                       <div  class="list-group-item" v-for="(user,index1) in contact.children" :key="user.id">
                       <el-checkbox v-if="isSelect"  v-model="user.cchecked" @change="updateChecked(user,index)"   style="margin-right: 10px"></el-checkbox>{{user.name}}  {{user.phone}}
                       </div>
          &lt;!&ndash;           </draggable>&ndash;&gt;
                   </el-collapse-item>

                 </el-collapse>-->
          <el-tree
            :data="contacts"
            :show-checkbox="isSelect"
            node-key="id"
            ref="menuListTree"
            :props="defaultProps">
          </el-tree>


        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  import draggable from "vuedraggable/src/vuedraggable";
  export default {
    name: "clone",
    display: "Clone",
    order: 2,
    components: {
      draggable
    },
    data() {
      return {
        defaultProps: {
          children: 'children',
          label: 'lable',
        },
        smsgNumber:1,
        smsgMessageWord:50,
        showHint:false,
        selectOrCancel:'选择',
        isSelect:false,
        param: {},
        codeStr:[],
        templateText:"",
        templateText1:"",
        tempKey: -666666, // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
        form: {
          template:'',
          text:'',
          code:''
        },
        sendMessage:{
          smsgMessageTemplate:{},
          contacts:[],
          content:""
        },
        textarea: '',
        templates: [],
        value: '',
        /*      contacts:[
                {
                  checked:false,
                  isOne:true,
                  children:[{
                    cchecked:false,
                    isOne:false,
                  }]

                }


              ],*/
        contacts:[],
        activeNames1: ['1'],
        list1: [
          { name: "组件1", id: 1, content: "内容内容内容。。。。" },
          { name: "组件2", id: 2, content: "内容内容内容。。。。" },
          { name: "组件3", id: 3, content: "内容内容内容。。。。" },
          { name: "组件4", id: 4, content: "内容内容内容。。。。" },
          { name: "组件5", id: 5, content: "内容内容内容。。。。" },
          { name: "组件6", id: 6, content: "内容内容内容。。。。" },
          { name: "组件7", id: 7, content: "内容内容内容。。。。" }
        ],
        list2: [],
        activeNames: [],
        count: 0,
        dataRule: {
          template: [{ required: true, message: '请选择模版', trigger: 'blur' }]
        }
      };
    },
    created() {
      this.getTemplateList();
      this.getgroup();
    },

    methods: {
      log: function (evt) {
        console.log(evt);
        if (evt.added) {
          this.count += 1;
          const item = evt.added.element;
          // 遍历原来的数组删除它
          /*        console.log(this.contacts)
                  for(var i=0;i<this.contacts.length;i++){
                    var contact=this.contacts[i].users;
                    for(var j=0;j<contact.length;j++){
                      if(item.id==contact[j].id){
                        this.contacts[i].users[j]={}
                      }
                    }
                  }*/
          const idx = this.list2.findIndex(e => e.id === item.id);
          let temp = JSON.parse(JSON.stringify(this.list2));
          temp[idx].id = this.count;
          this.list2 = temp;
        }
      },
      select(){
        if(this.isSelect==false){
          this.isSelect=true
          this.selectOrCancel="取消"

        }else {
          this.isSelect=false
          this.selectOrCancel="选择"
          this.$refs.menuListTree.setCheckedKeys([])
          this.list2=[]
        }

      },

      selecedContacts(){
        var ids=[].concat(this.$refs.menuListTree.getCheckedKeys(true,false)); //[].concat(this.$refs.menuListTree.getCheckedKeys(true,false),[this.tempKey])
        this.$http({
          url: this.$http.adornUrl('/smsgcontact/listByIds'),
          method: 'post',
          data: this.$http.adornData(ids,false),
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.list2=data.list;
            this.isSelect=false
            this.selectOrCancel="选择"
          } else {
          }
        })

      },

      updateChecked(object,index){
        if(object.isOne){
          // 选中的为组，选中下面的所有组
          for (let i = 0; i < this.contacts[index].children.length; i++) {
            this.contacts[index].children[i].cchecked=!(this.contacts[index].children[i].cchecked)
          }
        }
        console.log(this.contacts)
      },
      //获取组
      getgroup () {
        this.$http({
          url: this.$http.adornUrl('/smsggroup/group'),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.contacts=data.list;
            for (let i = 0; i < this.contacts.length; i++) {
              this.contacts[i].lable=this.contacts[i].name
              for (let j = 0; j <this.contacts[i].children.length; j++) {
                this.contacts[i].children[j].lable=this.contacts[i].children[j].name+" : "+this.contacts[i].children[j].phone
              }
            }
          } else {
          }
          console.log(this.contacts)
        })
      },
      deleteItem: function (index) {
        this.list2.splice(index, 1);
      },
      close(){
        this.$router.push({ path: '/smsgmessagelog' })
      },
      handleChange(val) {
        console.log(val);
      },
      changeTemplateText(value) {
        this.showHint=true
        this.dataRule={ template: [{ required: true, message: '请选择模版', trigger: 'blur' }]}
        for (var i = 0; i < this.templates.length; i++) {
          var template = this.templates[i];
          if (value === template.id) {
            this.templateText = template.content
            this.sendMessage.smsgMessageTemplate = template
            this.templateText1 = this.templateText
            this.codeStr = []
            this.smsgMessageWord=this.sendMessage.smsgMessageTemplate.content.length
          }
        }

        var content=this.sendMessage.smsgMessageTemplate.content
        var index = content.indexOf("${");
        if(index!=-1){
          this.codeStr=this.getCode(content);
          // 动态添加校验
          for (let i = 0; i < this.codeStr.length; i++) {
            this.dataRule[this.codeStr[i]]=[{ required: true, message: '请输入替换模版中${'+this.codeStr[i]+'}的值', trigger: 'blur' }]
          }
          var template1 = this.form.template;

          this.form={}
          this.form.template=template1
        }
        this.param = {}
        /*      var str = this.sendMessage.smsgMessageTemplate.replaceCode
              if (str != "") {
                var strs = new Array();
                strs = str.split(",")
                this.codeStr = strs;
              }*/

      },
      getCode(str){
        var reg = /\$\{(.+?)\}/g
        var list = []
        var result = null
        do {
          result = reg.exec(str)
          result && list.push(result[1])
        } while (result)
        return list
      },
      getTemplateList() {
        this.$http({
          url: this.$http.adornUrl('/smsg/smsgmessagetemplate/getListAll'),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.templates = data.templates;
          }
        })
      },
      replace(value) {
        if (this.templateText != "") {
          //替换模版中的${value}
          var text=this.templateText.format(this.form)
          this.templateText1 = text
          this.smsgMessageWord=this.templateText1.length;
          if(this.templateText1.length>70){
            this.smsgNumber=2
          }else {
            this.smsgNumber=1
          }
        }
      },
      test(value) {
        const item = value;
        console.log(item.id)
        const idx = this.list2.findIndex(
          e => e.id === item.id
        );
        console.log(idx)
        let temp = JSON.parse(JSON.stringify(this.list2));
        temp[idx].id = this.count;
        this.list2 = temp;
      },

      onSubmit() {
        this.sendMessage.contacts = this.list2;
        this.sendMessage.content = this.form.text

        for (let i = 0; i < this.codeStr.length; i++) {
          this.param[this.codeStr[i]]=this.form[this.codeStr[i]]
        }
        if(this.list2.length<=0){
          this.$message({
            message: '请选择联系人',
            type: 'error',
            duration: 1500,
          })
        }else if(this.list2.length>100){
          this.$message({
            message: '联系人不能超过100',
            type: 'error',
            duration: 1500,
          })
        }else {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.$http({
                url: this.$http.adornUrl('/smsg/SendSmsgMessage/sendSmsg'),
                method: 'post',
                data: this.$http.adornData({
                  'contacts': this.sendMessage.contacts,
                  'smsgMessageTemplate': this.sendMessage.smsgMessageTemplate,
                  'param': this.param,
                  'content':this.templateText1
                })
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: '发送成功',
                    type: 'success',
                    duration: 1500,
                  })
                  this.$router.push({ path: '/smsgmessagelog' })
                } else {
                  this.$message.error(data.msg)
                }
              })
            }
          })
        }



      }
    }
  };
  String.prototype.format = function() {
    if(arguments.length == 0) return this;
    var obj = arguments[0];
    var s = this;
    for(var key in obj) {
      s = s.replace(new RegExp("\\${" + key + "\\}", "g"), obj[key]);
    }
    return s;
  }


</script>
<style scoped>

  .list-group {
    display: flex;
    flex-direction: column;
    padding-left: 0;
    margin-bottom: 0;
    border: 0;
  }
  .list-group2 {
    display: flex;
    flex-wrap:wrap;
    flex-direction: row;
    padding-left: 0;
    margin-bottom: 0;
    border: 0;
  }

  .list-group-item:first-child {
    border-top-left-radius: 0.25rem;
    border-top-right-radius: 0.25rem;
  }

  .list-group-item {
    position: relative;
    display: block;
    padding: 0.75rem 1.25rem;
    margin-bottom: -1px;
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.125);
    box-sizing: border-box;
  }

  .list-group-item3 {
    position: relative;
    display: inline-block;
    padding: 0.75rem 1.25rem;
    margin-bottom: -1px;
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.125);
    box-sizing: border-box;
    width: 100px;
    border-radius: 25px;
    background-color: #ece3dc;
  }

  .el-collapse-item__header {
    border: 0;
  }



  .list-group-item {
    cursor: move;
  }

  h3 {
    font-size: 28px;
    margin-bottom: 20px;
  }

  .el-icon-circle-close {
    color: #c9a2a2;
    font-size: 20px;
    position: absolute;
    right: 30px;
    pointer-events: auto;
    line-height: 50px;

  }
  .item {
    margin-top: -16px;
    margin-right: -20px;
  }

  .el-icon-circle-close:hover {
    color: #f40;
  }

  .el-icon-arrow-right:before{

    dislpay:none !important;
    content: none;
    position:absolute;
    z-index:-999;
  }
  .el-collapse-item__arrow::before{
    dislpay:none !important;
  }

  .sortable-chosen{
    dislpay:none !important;
  }
  .sortable-ghost{
    dislpay:none !important;
  }
  .el-tree /deep/ .el-tree-node__content{
    position: relative;
    display: block;
    margin-bottom: -1px;
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.125);
    box-sizing: border-box;
    height: 40px;
    line-height: 40px;

  }


</style>
